#!/usr/bin/python

import sys
import re

def readline_exit(infile):
    """ Reads one line from open file and returns the line stripped of blanks
    or sys.exit() if it is the lsat line of the file """
    line= infile.readline()
    if line == '':
        sys.exit()
    else:
        return(line.strip())

def is_createtable(line):
    """ Returns True if line is he beginning of create table sql"""
    if line.startswith('CREATE TABLE '):
        return(True)
    else:
        return(False)

def is_createtable_end(line):
    """ Returns True if line ends with );"""
    line= line.strip()
    if line.endswith(');'):
        return(True)
    else:
        return(False)

def char2text(line):
    """ Replaces CHAR type to TEXT in line
    """
    line= re.sub('CHAR\(\d*\)|VARCHAR\(\d*\)', 'TEXT', line)
    return(line)
    
def comment_unnecessary(line):
    """ Comment out lines macthing unwanted items """
    line= line.strip()
    if line.startswith('ANALYZE') or line.startswith('INSERT INTO "sqlite_stat1" VALUES'):
        line= '-- ' + line
    return(line)
infile= open(sys.argv[1])

line= readline_exit(infile)
create_table= is_createtable(line)   ## Is line the first line of a create table statement

while True:
    while create_table is True:
        """ This while loop scans the lines of each CREATE TABLE statement """
        line= char2text(line)
        print(line)
        line= readline_exit(infile)
        create_end= is_createtable_end(line)
        if create_end is True:
            break
    line= comment_unnecessary(line)
    print(line)
    line= readline_exit(infile)
    create_table= is_createtable(line)
